The device on your wrist beeps several times, and once again you feel like you're falling.

"Situation critical," the device announces. "Destination indeterminate. Chronal interference detected. Please specify new target coordinates."

The device then produces a list of coordinates (your puzzle input). Are they places it thinks are safe or dangerous? It recommends you check manual page 729. The Elves did not give you a manual.

If they're dangerous, maybe you can minimize the danger by finding the coordinate that gives the largest distance from the other points.

Using only the Manhattan distance, determine the area around each coordinate by counting the number of integer X,Y locations that are closest to that coordinate (and aren't tied in distance to any other coordinate).

Your goal is to find the size of the largest area that isn't infinite. For example, consider the following list of coordinates:

1, 1
1, 6
8, 3
3, 4
5, 5
8, 9
If we name these coordinates A through F, we can draw them on a grid, putting 0,0 at the top left:

..........
.A........
..........
........C.
...D......
.....E....
.B........
..........
..........
........F.
This view is partial - the actual grid extends infinitely in all directions. Using the Manhattan distance, each location's closest coordinate can be determined, shown here in lowercase:

aaaaa.cccc
aAaaa.cccc
aaaddecccc
aadddeccCc
..dDdeeccc
bb.deEeecc
bBb.eeee..
bbb.eeefff
bbb.eeffff
bbb.ffffFf
Locations shown as . are equally far from two or more coordinates, and so they don't count as being closest to any.

In this example, the areas of coordinates A, B, C, and F are infinite - while not shown here, their areas extend forever outside the visible grid. However, the areas of coordinates D and E are finite: D is closest to 9 locations, and E is closest to 17 (both including the coordinate's location itself). Therefore, in this example, the size of the largest area is 17.

What is the size of the largest area that isn't infinite?

In [1]:
from collections import Counter, defaultdict

# Parses lines like "123, 123"
def parse(line):
    x, y = line.split(',')
    return int(x), int(y)

# Compute Manhattan distance
def distance((x1, y1), (x2, y2)):
    return abs(x1 - x2) + abs(y1 - y2)    

# Nearst location to p or None if there is more than one location at the same distance
def nearest(p, locations):
    distances = defaultdict(list)
    for l in locations:
        distances[distance(l, p)].append(l)
        
    min_distance = min(distances.keys())
    
    # Don't count positions with more than one location at the same distance    
    if len(distances[min_distance]) > 1:
        return None
    
    return distances[min_distance][0]

# Returns True if the (x, y) location is surrounded
def has_finite_area((x, y), locations):
    
    directions = [    
        (i, j) -> (i < x) and (j < y),  # northeast
        (i, j) -> (i < x) and (j > y),  # southeast
        (i, j) -> (i > x) and (j < y),  # northwest
        (i, j) -> (i > x) and (j > y)   # southwest
    ]
    
    for d in directions:        
        
        # If there is no other location at one direction
        # it will have an infinite area
        if sum(1 for i, j in locations if d(i, j)) == 0:
            return False
    
    return True

# Returns and iterator of all the coordinates in the area of interest
def area_to_explore(locations):
    
    # Area borders
    north = min(l[1] for l in locations) 
    south = max(l[1] for l in locations) 
    east  = min(l[0] for l in locations) 
    west  = max(l[0] for l in locations) 

    # All area coordinates
    return ((x, y) for x in range(east, west+1) for y in range(north, south+1))    

# Returns the maximum area of a surrounded location
def maximum_finite_area(locations):        
    
    # Count the area
    areas = Counter(locations |> area_to_explore |> fmap$(nearest$(?, locations)))        
    
    # Find locations that has a finite area
    finite_locations = locations |> filter$(has_finite_area$(?, locations)) |> list
    
    # Return the biggest area belonging to a finite area location
    return max(areas[l] for l in finite_locations)

In [2]:
# Test the example
example = ["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]
example |> fmap$(parse) |> maximum_finite_area


Out[2]:
17

In [3]:
# Compute input
open("input/day06.txt") |> fmap$(parse) |> maximum_finite_area


Out[3]:
3010
--- Part Two ---
On the other hand, if the coordinates are safe, maybe the best you can do is try to find a region near as many coordinates as possible.

For example, suppose you want the sum of the Manhattan distance to all of the coordinates to be less than 32. For each location, add up the distances to all of the given coordinates; if the total of those distances is less than 32, that location is within the desired region. Using the same coordinates as above, the resulting region looks like this:

..........
.A........
..........
...###..C.
..#D###...
..###E#...
.B.###....
..........
..........
........F.
In particular, consider the highlighted location 4,3 located at the top middle of the region. Its calculation is as follows, where abs() is the absolute value function:

Distance to coordinate A: abs(4-1) + abs(3-1) =  5
Distance to coordinate B: abs(4-1) + abs(3-6) =  6
Distance to coordinate C: abs(4-8) + abs(3-3) =  4
Distance to coordinate D: abs(4-3) + abs(3-4) =  2
Distance to coordinate E: abs(4-5) + abs(3-5) =  3
Distance to coordinate F: abs(4-8) + abs(3-9) = 10
Total distance: 5 + 6 + 4 + 2 + 3 + 10 = 30
Because the total distance to all coordinates (30) is less than 32, the location is within the region.

This region, which also includes coordinates D and E, has a total size of 16.

Your actual region will need to be much larger than this example, though, instead including all locations with a total distance of less than 10000.

What is the size of the region containing all locations which have a total distance to all given coordinates of less than 10000?

In [4]:
# Check that a is in a safe region with distance less than safe_distance
def is_in_safe_region(a, locations, safe_distance):
    total_distance = locations |> fmap$(distance$(?, a)) |> sum
    return total_distance < safe_distance

# Returns and iterator over all safe coordinates
def locations_in_safe_region(locations, safe_distance):    
    return area_to_explore(locations) |> filter$(is_in_safe_region$(?, locations, safe_distance))

In [5]:
example |> fmap$(parse) |> locations_in_safe_region$(?, 32) |> list |> len


Out[5]:
16

In [6]:
open("input/day06.txt") |> fmap$(parse) |> locations_in_safe_region$(?, 10000) |> list |> len


Out[6]:
48034